package com.sinaapp.zhangziyou.action;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sinaapp.zhangziyou.pojo.UserEntity;
import com.sinaapp.zhangziyou.service.UCenterService;

@Controller
public class PwdGetBackController {
	private static Logger logger = LoggerFactory.getLogger(PwdGetBackController.class);

	@Autowired
	private UCenterService uCenterService;

	@RequestMapping("/pwdGetBack")
	public String pwdGetBack() {
		return "pwdGetBack";
	}

	@RequestMapping("/sendEmail")
	public String sendEmail(Model model, String email) {
		boolean exist = uCenterService.checkEmailIsExist(email);
		if(exist){
			uCenterService.sendPwdGetBackEmail(email);
			model.addAttribute("tips", "邮件发送成功！！");
		} else {
			model.addAttribute("tips", "邮件无效！！");
		}
		return "tip";
	}
	
	@RequestMapping("/verifyCode")
	public String verifyCode(Model model, String code) {
		boolean codeIsRight = uCenterService.checkCode(code);
		if(codeIsRight){
			model.addAttribute("code", code);
			return "passwordReset";
		}else{
			model.addAttribute("tips", "链接失效了！！");
			return "tip";
		}
	}

	@RequestMapping("/passwordReset")
	public String passwordReset(Model model,String code, String passWord1) {
		String userId = uCenterService.getUserIdByCode(code);
		if(userId != null && !userId.isEmpty()){
			UserEntity user = uCenterService.getUser(userId);
			user.setPassWord(passWord1);
			boolean success = uCenterService.saveUser(user);
			if(success){
				model.addAttribute("tips", "密码修改成功！！");
			}else{
				model.addAttribute("tips", "密码修改失败！！");
			}
			uCenterService.deleteEmailValEntityByCode(code);
		}else{
			model.addAttribute("tips", "请通过邮件重置！！");
		}
		return "tip";
	}
	
	public UCenterService getuCenterService() {
		return uCenterService;
	}

	public void setuCenterService(UCenterService uCenterService) {
		this.uCenterService = uCenterService;
	}
}
